<?php
namespace app\weapp\controller;

use app\common\controller\Weapp;
use app\weapp\library\WeAppApi;
use EasyWeChat\Work\Application;
use app\common\model\Member;
use think\facade\Db;
use app\admin\model\HrField;
use app\admin\model\HrFieldType;
use app\admin\model\HrGroupList;
use think\facade\Log;
use app\common\model\Inform;
class Notice extends Weapp
{
    /**
     * 无需登录的方法
     * 访问本控制器的此方法，无需会员登录
     * @var array
     */
    protected array $noNeedLogin = ['auth','index','user','detail','login','userverify','formitem'];

    /**
     * 无需鉴权的方法
     * @var array
     */
    protected array $noNeedPermission = ['auth','index','user','detail','login','userverify','formitem'];
    public function initialize():void
    {
        parent::initialize();
    }

    public function index(){
        $page = $this->request->param('page',1);
        $pageSize = $this->request->param('page_size',20);
        $list = Inform::where('status',1)->page($page,$pageSize)->select();
        foreach ($list as $key => &$value) {
            $value['create_time'] = date('Y-m-d H:i',$value['create_time']);
        }
        $this->success('',$list);
    }

     public function detail(){
        $id = $this->request->param('id','');
        $info = Inform::find($id);
        $info->views = Db::raw('views+1');
        $info->save();
        $info['images'] = $info['images']?explode(',',$info['images']):[];
        if($info['image']){
            $info['images'][] = $info['image'];
        }
        $this->success('',$info);
    }
    public function auth(){
        $agent_id = $this->request->param('agent_id','');
        $config = [
            'corp_id' => 'ww5d7b19c3c1ce8e1f',
            'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE',
            
        ];
        $app = new Application($config);
        $utils = $app->getUtils();
        if(empty($agent_id)){
            $config = $utils->buildJsSdkConfig('https://wework.sdlycwzx.com/notice/',['hideOptionMenu','createWWLoginPanel'],[]);
            $data['timestamp'] = $config['timestamp'];
            $data['nonceStr'] = $config['nonceStr'];
            $data['signature'] = $config['signature'];
        }else{
            $data = $utils->buildJsSdkAgentConfig($agent_id,'https://wework.sdlycwzx.com/notice/',['hideOptionMenu','createWWLoginPanel'], []);
        }
        
        //{ timestamp, nonceStr, signature }
        $this->success('',$data);
    }
    public function user(){
        Log::info('notice:user');
        $member = $this->auth->getInfo();
        $token = $this->auth->getToken();
        $this->success('',$member);
    }
    
    public function login(){
        $code = $this->request->param('code','');
        if($code){
            $config = [
                'corp_id' => 'ww5d7b19c3c1ce8e1f',
                'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE',
                'http'=>['throw'=>false],
            ];
            $app = new Application($config);
            $user = $app->getOAuth()->detailed()->userFromCode($code);
            Log::info('userOauth:'.json_encode($user));
            if(isset($user['errcode']) && $user['errcode'] != 0){
                $this->error('登录认证错误');
            }
            $userinfo = $user->getRaw();
            $member = Member::getByUserId($userinfo['userid']);
            
            if(empty($member)){
                 $this->success('未注册用户',['user_id'=>$userinfo['userid'],'nickname'=>$userinfo['name'],'is_auth'=>0,'is_show'=>0]);
            }
            Log::info('member:'.json_encode($member));
            $member->nickname = $userinfo['name'];
            $member->save();
            if($member->is_auth == 1){
                //?access_token=ACCESS_TOKEN&userid=USERID
                $api = $app->getClient();
                $response = $api->get('https://qyapi.weixin.qq.com/cgi-bin/user/authsucc',['userid'=>$userinfo['userid']]);
            }
            $user = $member->hidden(['create_time','update_time','status'])->toArray();
            Log::info('user:'.json_encode($user));
            if(empty($user['form_20008'])){
                $this->success('未注册用户',['id'=>$user['id'],'user_id'=>$userinfo['userid'],'nickname'=>$userinfo['name'],'is_auth'=>0,'is_show'=>0]);
            }else{
                $user['is_show'] = 1;
            }
            
            $this->success('已注册用户',$user);
        }
    }
    
    public function userverify(){
        if($this->request->isPost()){
            $data = $this->request->post();
            Log::info(json_encode($data));
            $upconfig = [
                'corp_id'=>'ww5d7b19c3c1ce8e1f',
                'secret' => 'Z7kR0_MhnYYq1VRC_6TfPGIiOnsBsyHw9s5_bdt9WnM',
                'token' => 'DGJ25KSmpioWpC12PfOnnLv',
                'aes_key' => '5Aot5xz53NdLsgtzoILpVDtytsYW4f5AgDOYekKdL5l',
            ];
            $upApp = new Application($upconfig);
            $upapi = $upApp->getClient();
           
            if(isset($data['id']) && $data['id']){
                $member = Member::find($data['id']);
                
                if(!empty($member['form_20012'])){
                    $department[] = intval($member['form_20012'])+1;
                    $upapi->postJson('https://qyapi.weixin.qq.com/cgi-bin/user/update',[
                        "userid"=> $data['user_id'],
                        "department"=>[
                               $department
                            ]
                    ]);
                }
            }else{
                $member = new Member;
                 $upapi->postJson('https://qyapi.weixin.qq.com/cgi-bin/user/update',[
                    "userid"=> $data['user_id'],
                    "department"=>[1]
                ]);
            }
            $member->save($data);
            
            $config = [
                'corp_id' => 'ww5d7b19c3c1ce8e1f',
                'secret' => 'pOBrwunxH-2otSIwR_6FKQjhXn0XAEiKX0z_q93u1xE',
            ];
            
            $app = new Application($config);
            $api = $app->getClient();
            $response = $api->get('https://qyapi.weixin.qq.com/cgi-bin/user/authsucc',['userid'=>$data['user_id']]);
            $this->success();
        }
    }
    
    public function formitem(){
        $list = Db::name('HrFieldValue')->where('1=1')->select();
        $data = [];
        foreach ($list as $key => $value){
            $data['form_'.$value['field_id']][]=['id'=>$value['weigh'],'lable'=>$value['value'],'code'=>'form_'.$value['field_id']];
        }
        $this->success('',$data);
    }
}